package io.gitee.kotle.android.iInterface

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry

/**
 *
 * 描述：
 *
 * @author jiale.wei
 *
 * 创建时间：2022/7/14 14:33
 *
 */
interface ILifecycleOwner : LifecycleOwner {
    class Impl : ILifecycleOwner {
        private var _lifecycleRegistry: LifecycleRegistry? = null
        override val lifecycleRegistry: LifecycleRegistry
            get() = _lifecycleRegistry ?: LifecycleRegistry(this).also {
                _lifecycleRegistry = it
            }
    }

    /**
     * LifecycleRegistry
     */
    val lifecycleRegistry: LifecycleRegistry

    /**
     * Lifecycle
     */
    override val lifecycle: Lifecycle
        get() = lifecycleRegistry

    /**
     * 分发Create
     */
    fun dispatchOnCreate() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_CREATE)
    }

    /**
     * 分发Start
     */
    fun dispatchOnStart() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_START)
    }

    /**
     * 分发Resume
     */
    fun dispatchOnResume() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_RESUME)
    }

    /**
     * 分发Pause
     */
    fun dispatchOnPause() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    }

    /**
     * 分发Stop
     */
    fun dispatchOnStop() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_STOP)
    }

    /**
     * 分发Destroy
     */
    fun dispatchOnDestroy() {
        dispatchLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }

    /**
     * 分发状态
     */
    fun dispatchLifecycleEvent(event: Lifecycle.Event) {
        lifecycleRegistry.handleLifecycleEvent(event)
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_ANY)
    }
}